package cn.aitrox.ry.util;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.Map;

public class LogUtil {
    public static String gen(String message, String body) {
        if (Strings.isNullOrEmpty(message))
            return body;
        else
            return String.format("%s : %s", message, body);
    }

    public static String gen(String message, Object body) {
        return gen(message, (body == null) ? "" : body.toString());
    }

    /**
     * 至少有一个，数量是奇数
     * 
     * @param message
     * @param args message, key1, value1, key2, value2...
     * @return
     */
    public static String gen(String message, String... args) {
        if (args == null || args.length % 2 == 1)
            return "GEN ERROR";
        return gen(message, Lists.newArrayList(args));
    }

    public static String gen(String message, List<String> args) {
        List<String> sl = Lists.newArrayList();
        for (int i = 0; i < args.size();) {
            sl.add(String.format("%s=[%s]", args.get(i), args.get(i + 1)));
            i = i + 2;
        }
        return genList(message, sl);
    }

    public static String gen(String message, Map<String, String> args) {
        List<String> sl = Lists.newArrayList();
        for (Map.Entry<String, String> entry : args.entrySet()) {
            sl.add(String.format("%s=[%s]", entry.getKey(), entry.getValue()));
        }
        return genList(message, sl);
    }

    public static String genException(Exception e) {
        List<String> args = Lists.newArrayList();
        args.add("msg");
        args.add(e.getMessage());
        args.add("stack");
        args.add(Throwables.getStackTraceAsString(Throwables.getRootCause(e)));
        return gen("", args);
    }

    public static String genException(Exception e, String message, String... args) {
        return LogUtil.gen(LogUtil.gen(message, args), LogUtil.genException(e));
    }

    private static String genList(String message, List<String> sl) {
        String body = Joiner.on(", ").useForNull("").join(sl);
        return gen(message, body);
    }
}
